package com.ternnetwork.core.aop;

import org.apache.commons.beanutils.BeanUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Component
@Aspect
@Order(1)
@Slf4j
public class ProcessTimeAspect {

    private static final String PROCESS_TIME="processTime";




    /**
     * 定义一个切入点.
     * 解释下：
     *
     * ~ 第一个 * 代表任意修饰符及任意返回值.
     * ~ 第二个 * 定义在web包或者子包
     * ~ 第三个 * 任意方法
     * ~ .. 匹配任意数量的参数.
     */
    @Pointcut("execution(* com.ternnetwork.core..*controller..*.*(..))")
    public void processTimePointcut(){
    }
    @Around("processTimePointcut()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable{

        long start = System.currentTimeMillis();

        String controllerClass = joinPoint.getTarget().getClass().getName();

        Class<?> clazz = Class.forName(controllerClass);

        String clazzSimpleName = clazz.getSimpleName();

        try {
            Object result = joinPoint.proceed();

            long end = System.currentTimeMillis();

            long processTime=end-start;
            //设置调用耗时
            BeanUtils.setProperty(result, PROCESS_TIME, String.valueOf(processTime));

           // log.info(clazzSimpleName+"."+joinPoint.getSignature().getName()+" processTime:"+processTime+" ms");

            return result;
        }
        catch (Throwable e) {

            throw e;
        }
    }

}